package model

import (
	"gorm.io/gorm/clause"
)

func QueryGoodById(goodId string) *Good {
	res := Good{}
	if err := GlobalDB.First(&res, "good_id = ?", goodId).Error; err != nil {
		return nil
	}
	return &res
}

// QueryGoodByName 用于查看是否有重名，实际搜索使用 ES
func QueryGoodByName(goodName string) *Good {
	res := Good{}
	if err := GlobalDB.Unscoped().First(&res, "name = ?", goodName).Error; err != nil {
		return nil
	}
	return &res
}

func QueryGoodCount(stat string) (int64, error) {
	var count int64
	err := GlobalDB.Model(&Good{}).Where("state = ?", stat).Count(&count).Error
	return count, err
}

// QueryGoods stat 可以选择是否下架的商品，可选项 online/offline
func QueryGoods(stat, isPart string, offset, num int) []Good {
	var res []Good
	if isPart == "0" {
		GlobalDB.Where("state = ?", stat).Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: "created",
			},
			Desc: false,
		}).Find(&res)
	} else {
		GlobalDB.Where("state = ?", stat).Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: "created",
			},
			Desc: false,
		}).Offset(offset).Limit(num).Find(&res)
	}
	return res
}

func InsertGood(good *Good) error {
	return GlobalDB.Create(good).Error
}

func UpdateGood(good *Good) error {
	return GlobalDB.Updates(good).Error
}

func DeleteGood(goodId string) error {
	return GlobalDB.Delete(&Good{}, "good_id = ?", goodId).Error
}
